package com.growthgate.bootcommon.handler;

import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.collect.Sets;
import com.growthgate.bootcommon.common.ResponseResult;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;

import javax.annotation.Resource;

/**
 * API操作处理器
 *
 * @author GrowthGate
 * @date 2020/2/25
 */
@Component
public class ApiOperationHandler implements OperationBuilderPlugin {

    @Resource
    private TypeResolver typeResolver;

    @Override
    public void apply(@NotNull OperationContext context) {
        // 获取响应类型
        Class<?> erasedType = context.getReturnType().getErasedType();
        if (erasedType != ResponseResult.class) {
            // 生成ResponseResult对应类型的ResolvedType
            ResolvedType resolve = typeResolver.resolve(ResponseResult.class, erasedType);
            context.getDocumentationContext().getAdditionalModels().add(resolve);

            String erasedName = erasedType != void.class ? erasedType.getSimpleName() : "null";
            ModelRef modelRef = new ModelRef("ResponseResult«" + erasedName + "»");
            ResponseMessage responseMessage = new ResponseMessageBuilder().code(200).responseModel(modelRef).build();
            // 修改响应的model和message
            context.operationBuilder().responseModel(modelRef).responseMessages(Sets.newHashSet(responseMessage));
        }
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return true;
    }

}